package io.jpress.commons.word.hwpf;

import com.jfinal.core.JFinal;
import io.jboot.utils.FileUtil;
import io.jboot.utils.QuietlyUtil;
import io.jboot.utils.StrUtil;
import io.jboot.web.attachment.AttachmentManager;
import org.apache.poi.hwpf.converter.AbstractWordUtils;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Picture;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import java.io.File;
import java.io.FileOutputStream;

public class InlineImageWordToHtmlConverter extends WordToHtmlConverter {

    public InlineImageWordToHtmlConverter(Document document) {
        super(document);
    }

    class Triplet {
        public String fontName;
        public boolean bold;
        public boolean italic;
    }

    protected Triplet getCharacterRunTriplet1(CharacterRun characterRun) {
        Triplet original = new Triplet();
        original.bold = characterRun.isBold();
        original.italic = characterRun.isItalic();
        original.fontName = characterRun.getFontName();
        return DefaultFontReplacer.update(original);
    }


    @Override
    protected void outputCharacters(Element pElement,
                                    CharacterRun characterRun, String text) {
        Element span = getDocument().createElement("span");
        pElement.appendChild(span);

        StringBuilder style = new StringBuilder();
//        BlockProperies blockProperies = this.blocksProperies.peek();
        Triplet triplet = getCharacterRunTriplet1(characterRun);

        if (StrUtil.isNotEmpty(triplet.fontName)) {
            style.append("font-family:").append(triplet.fontName).append(";");
        }
//        if ( characterRun.getFontSize() / 2 != blockProperies.pFontSize )
//        {
        style.append("font-size:").append(characterRun.getFontSize() / 2).append("pt;");
//        }
        if (triplet.bold) {
            style.append("font-weight:bold;");
        }
        if (triplet.italic) {
            style.append("font-style:italic;");
        }

        WordToHtmlUtils.addCharactersProperties(characterRun, style);
        if (style.length() != 0) {
//            htmlDocumentFacade.addStyleClass( span, "s", style.toString() );
            span.setAttribute("style", style.toString());
        }

        Text textNode = getDocument().createTextNode(text);
        span.appendChild(textNode);
    }


    @Override
    protected void processImageWithoutPicturesManager(Element currentBlock,
                                                      boolean inlined, Picture picture) {

        final float aspectRatioX = picture.getHorizontalScalingFactor();
        final float aspectRatioY = picture.getVerticalScalingFactor();


        float imageWidth = picture.getDxaGoal();
        if (aspectRatioX > 0) {
            imageWidth *= aspectRatioX / 1000f;
        }
        imageWidth /= AbstractWordUtils.TWIPS_PER_INCH;

        float imageHeight = picture.getDyaGoal();
        if (aspectRatioY > 0) {
            imageHeight *= aspectRatioY / 1000f;
        }
        imageHeight /= AbstractWordUtils.TWIPS_PER_INCH;


        imageWidth *= 100;
        imageHeight *= 100;


        Element imgNode = currentBlock.getOwnerDocument().createElement("img");
        imgNode.setAttribute("style", "width:" + imageWidth + "px;height:" + imageHeight + "px;");


        File newFile = AttachmentManager.me().createNewFile(getSuffix(picture.getMimeType()));
        FileOutputStream fos = null;
        try {
            FileUtil.ensuresParentExists(newFile);
            fos = new FileOutputStream(newFile);
            fos.write(picture.getRawContent());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            QuietlyUtil.closeQuietly(fos);
        }

        imgNode.setAttribute("src", JFinal.me().getContextPath() + AttachmentManager.me().getRelativePath(newFile));
        currentBlock.setAttribute("style", "text-align:center");
        currentBlock.appendChild(imgNode);
    }


    private String getSuffix(String mimeType) {
        if (StrUtil.isBlank(mimeType)) {
            return ".jpg";
        }

        if ("image/png".equals(mimeType)) {
            return ".png";
        }

        if ("image/jpeg".equals(mimeType)) {
            return ".jpeg";
        }

        return ".jpg";
    }

}